// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
	
	async getmodelAction(){
		let pid = this.get('pid');
		let list = await this.model('or_rulemodel').where({pid:pid}).select();
		return this.json(list);
	}

	//编辑规则
	async editruleAction(){
		if(this.isPost){
			let data = this.post();
			let is_exist = await this.model('or_rulegroup').where({groupid:data.groupid,grouptype:data.grouptype}).find();
			let res;
			if(!think.isEmpty(is_exist)){
				data.id = is_exist.id;
				res = await this.model('or_rulegroup').where({id:data.id}).update(data);
			}else{
				res = await this.model('or_rulegroup').add(data);
			}
			return res?this.success({info:"操作成功！"}):this.fail('操作失败！');
		}

		let id = this.get('id');
		let grouptype = this.get('grouptype');
		let uinfo = await this.model('or_rulegroup').where({groupid:id,grouptype:grouptype}).find();

		//取出当前所有模块和规则集合
		let modelurl = await this.model('or_rulemodel').select();

		return this.json({
			mlist:modelurl,
			usermodellist:uinfo.modelarr || '{}',
		});
	}

	// 获取权限管理
	async getruleAction(){
		let id = this.get('id');

		let list = await this.model('or_rulemodel').where({category: ["IN", [5, 6]]}).select();

		let permission = await this.model('or_rule_admin').where({id: id}).getField('gradepermission', true);

		let data = {
			rule : list,
			permission : permission
		}

		return this.json(data);
	}

	/*// 增加权限板块
	async addruleAction(){
		let rule = this.post();
		let data;
		if (rule.pid) {
			data = {
				name : rule.name,
				tags : rule.tags,
				category : rule.category,
				pid : rule.pid,
			}
			let res = await this.model('or_rulemodel').add(data);
			return res?this.success({info:'添加成功'}):this.fail('添加失败');
		}
		data = {
			name : rule.name,
			category : rule.category,
		}
		let res = await this.model('or_rulemodel').add(data)
		return res?this.success({info:'添加成功'}):this.fail('添加失败');
	}

	// 删除权限板块
	async deleteruleAction(){
		let delstr = JSON.parse(this.post('delarr'));

		let delpermisstionarr = [], delMiss = [];
		for (var i = 0, delstrLen = delstr.length; i < delstrLen; i++) {
			delpermisstionarr.push(await this.model('or_rulemodel').where({pid:delstr[i]}).getField('id'));
		}
		if (!think.isEmpty(delpermisstionarr)) {
			for (var i = 0, permissionLen = delpermisstionarr.length; i < permissionLen; i++) {
				delMiss = delMiss.concat(delpermisstionarr[i]);
			}
		}

		let model = this.model('or_rulemodel');
		await model.transaction(async ()=>{
			try {
				let dm = 1,dl = 1;
				if (!think.isEmpty(delMiss)) {
					for (var i = 0, missLen = delMiss.length; i < missLen; i++) {
						dm = await model.where({id:delMiss[i]}).db(model.db()).delete();
					}
				}

				for (var i = 0, arrLen = delstr.length; i < arrLen; i++) {
					dl = await model.where({id:delstr[i]}).db(model.db()).delete();
				}

				if (dm&&dl) {
					model.commit();
					return this.success({info:'删除成功'});
				}
			} catch(e) {
				console.log(e);
				model.rollback();
				return this.fail('删除失败');
			}
		})
	}*/

	// 删除权限功能
	async deletepermissionAction(){
		let delarr = JSON.parse(this.post('delarr'));
		let res = await this.model('or_rulemodel').where({id:['IN',delarr]}).delete();
		return res?this.success({info:'删除成功'}):this.fail('删除失败');
	}

	// 取出管理组的等级分配
	async getgradeallotAction(){
		let shopid = this.shop_userinfo.departmentid;
		let list = await this.model('or_rule_admin').where({departmentid:shopid}).order('gradeid ASC').select();
		return this.json(list);
	}

	// 新增权限
	async addotherpermissionAction(){
		let data = this.post();
		let shopid = this.shop_userinfo.departmentid;
		let time = Math.round(new Date().valueOf()/1000);

		if (data.id*1) {
			let chong = await this.model('or_rule_admin').where({departmentid: shopid, gradeid: data.gradeid, id: ['!=', data.id]}).select();
			if (!think.isEmpty(chong)) {
				return this.fail('权限等级重复');
			}

			let isuse = await this.model('or_admin').where({departmentid: shopid, groupid: data.id}).select();
			if (!think.isEmpty(isuse)) {
				return this.fail('当前权限已被使用，不能修改');
			}

			let gengxin = await this.model('or_rule_admin').where({id: data.id}).update({remarks:data.remarks, gradeid: data.gradeid, edittime: time});

			return gengxin?this.success('编辑成功'):this.fail('编辑失败');
		}

		let numbers = await this.model('or_rule_admin').where({departmentid: shopid}).select();
		if (numbers.length > 10) {
			return this.fail('新增权限等级已达上线');
		}

		let repeat = await this.model('or_rule_admin').where({departmentid: shopid, gradeid: data.gradeid}).select();
		if (!think.isEmpty(repeat)) {
			return this.fail('新增权限等级重复');
		}
		data.gradepermission = '[]';
		data.edittime = time;
		data.departmentid = shopid;

		let res = await this.model('or_rule_admin').add(data);
		return res?this.success('添加成功'):this.fail('添加失败');
	}

	// 修改后台权限
	async editadminpermissionsAction(){
		let data = this.post();

		let res = await this.model('or_rule_admin').where({id: data.id}).update({
			gradepermission: data.pers,
			edittime: Math.round(Date.now()/1000)
		});
		
		return res?this.success({info:'修改成功'}):this.fail('修改失败');
	}

	// 删除其他权限
	async deleteothergradeAction(){
		let id = this.post('id');
		let shopid = this.shop_userinfo.departmentid;

		let isuse = await this.model('or_admin').where({departmentid: shopid, groupid: id}).select();
		if (!think.isEmpty(isuse)) {
			return this.fail('权限已被使用不能删除');
		}
		let res = await this.model('or_rule_admin').where({id:id}).delete();
		return res?this.success('删除成功'):this.fail('删除失败');
	}

	// 设置店家账户权限
	async shopselectgradeAction(){
		let data = this.post();
		let res = await this.model('or_admin').where({id: data.id}).update({groupid: data.groupid});
		return res?this.success('修改成功'):this.fail('修改失败');
	}

	// 获取店家管理员
	async getadminlistAction(){

		let shopid = this.shop_userinfo.departmentid;

		let list = await this.model('or_admin')
				.alias('oa')
				.field('oa.*,ra.gradeid')
				.join('think_or_rule_admin ra on ra.id = oa.groupid')
				.where({'oa.departmentid':shopid, 'oa.ismain':0})
				.order('oa.id DESC')
				.select();
		return this.json(list);
	}

	// 添加分店管理员
	async addshopadminAction(){
		let data = this.post();
		let shopid = this.shop_userinfo.departmentid;

		if (data.id*1) {
			let chongfu = await this.model('or_admin').where('(username="'+data.username+'" OR phone="'+data.phone+'") AND id !='+data.id).select();
			if (!think.isEmpty(chongfu)) {
				return this.fail('帐号或手机号重复');
			}
			data.password = think.md5(data.password);
			let gengxin = await this.model('or_admin').where({id: data.id}).update(data);
			return gengxin?this.success('编辑成功'):this.fail('编辑失败');
		}

		let numbers = await this.model('or_admin').where({departmentid: shopid, ismain: 0}).select();
		if (numbers.length > 15) {
			return this.fail('添加的管理员已达上线');
		}

		let is_username = await this.model('or_admin').where('username="'+data.username+'" OR phone="'+data.phone+'"').find();
		if (!think.isEmpty(is_username)) {
			return this.fail('帐号或手机号重复');
		}
		data.departmentid = shopid;
		data.password = think.md5(data.password);
		let res = await this.model('or_admin').add(data);
		return res?this.success('添加成功'):this.fail('添加失败');
	}

	// 删除店家管理员
	async delshopadminAction(){
		let id = this.post('id');
		let res = await this.model('or_admin').where({id:id}).delete();
		return res?this.success({info:'删除成功'}):this.fail('删除失败');
	}
}